package pers.bc.utils.yonyou;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import nc.bs.framework.common.RuntimeEnv;
import nc.secutity.toolkit.SignatureTookKit;
import nc.uap.lfw.core.LfwRuntimeEnvironment;
import nc.uap.portal.task.itf.ITaskQryTmp;
import nc.uap.portal.task.ui.TaskHelper;
import nc.uap.wfm.engine.TaskProcessUI;
import nc.vo.pub.BusinessException;
import pers.bc.utils.encrypt.Base64;
import pers.bc.utils.file.FileUtilbc;
import pers.bc.utils.pub.LoggerUtil;
import pers.bc.utils.pub.PropertiesUtil;

/**
 * 单点登录
 * @qualiFild nc.pub.itf.tools.net.NCSSOUtil.java<br>
 * @author：licheng<br>
 * @date Created on 2019-10-15<br>
 * @version 1.0<br>
 */
public class NCSSOUtil
{
    private Map<String, String> configMap = null;
    private static NCSSOUtil SSOKeyUtil = null;
    
    /**
     * 调用接口获取token
     * 
     * @param url 要调用的接口
     * @param write 需要写出的数据
     * @return token值
     * @throws Exception
     */
    public static String getToken(String url, String write) throws Exception
    {
        OutputStream outStream = null;
        DataOutputStream dataOutput = null;
        InputStream inStream = null;
        String ret = "";
        try
        {
            URL preUrl = new URL(url);
            URLConnection con = preUrl.openConnection();
            // 设置为true，后面可以调用getOutputStream并传输数据
            con.setDoOutput(true);
            // 不使用http缓存
            con.setUseCaches(false);
            // 设置http请求头
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("Content-Length", "10000");
            HttpURLConnection httpCon = (HttpURLConnection) con;
            // 这里使用post方式调用接口
            httpCon.setRequestMethod("POST");
            // 获取输出流
            outStream = httpCon.getOutputStream();
            dataOutput = new DataOutputStream(outStream);
            // 接口需要的参数作为字节序列写入输出流
            dataOutput.writeBytes(write);
            dataOutput.flush();
            // 获取输入流
            inStream = httpCon.getInputStream();
            // 读取服务返回的数据
            int ch;
            while ((ch = inStream.read()) != -1)
            {
                ret += String.valueOf((char) ch);
            }
        }
        catch (Exception e)
        {
            throw new BusinessException("获取token结果异常，參數：" + write, e);
        }
        finally
        {
            // 关闭服务输入流和输出流
            FileUtilbc.close(dataOutput, outStream, inStream);
        }
        
        // 返回获取到的token
        return ret;
    }
    
    /**
     * *********************************************************** <br>
     * *说明：registerServlet 对对应的Servlet:LfwSsoRegisterServlet <br>
     * @see <br>
     * @param local
     * @param datasouce
     * @param userid
     * @return
     * @throws Exception <br>
     * @String <br>
     * @methods pers.bc.utils.yonyou.NCSSOUtil#getTokenByNc <br>
     * @author LiBencheng <br>
     * @date Created on 2025年6月6日 <br>
     * @time 上午11:30:55 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static String getTokenByNc(String baseurl, String datasouce, String userid) throws Exception
    {
        String ts = (System.currentTimeMillis() + "").substring(0, 6);
        String token = "";
        String registryUrl = baseurl + "/portal/registerServlet";// 注册用内网地址
        StringBuffer parameters = new StringBuffer("");
        parameters.append("&type=2");
        parameters.append("&dsname=" ).append( datasouce);
        parameters.append("&userid=" ).append( userid);
        parameters.append("&ts=").append(ts);
        // parameters.append("&password=123qwe");
        parameters.append("&needverifypasswd=").append("N");
        parameters.append("&loginsuccess=").append("y");
        // 构造NC注册URL
        URL preUrl = new URL(registryUrl);
        URLConnection uc = preUrl.openConnection();
        // 表明程序必须把名称/值对输出到服务器程序资源
        uc.setDoOutput(true);
        // 表明只能返回有用的信息
        uc.setUseCaches(false);
        // 设置Content-Type头部指示指定URL已编码数据的窗体MIME类型
        uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // 设置Content-Type头部指示指定URL已编码数据的窗体MIME类型
        uc.setRequestProperty("Content-Length", "" + parameters.length());
        // 提取连接的适当的类型
        HttpURLConnection hc = (HttpURLConnection) uc;
        // 把HTTP请求方法设置为POST（默认的是GET）
        hc.setRequestMethod("POST");
        // 输出内容
        OutputStream os = hc.getOutputStream();
        DataOutputStream dos = null;
        InputStream is = null;
        try
        {
            dos = new DataOutputStream(os);
            // out.print(parameters.toString());
            dos.writeBytes(parameters.toString());
            dos.flush();
            // 获取NC对凭证的验证结果
            is = hc.getInputStream();
            
            int ch;
            while ((ch = is.read()) != -1)
            {
                token += String.valueOf((char) ch);
            }
        }
        catch (Exception e)
        {
            throw new BusinessException("获取NC验证token结果异常，參數：" + parameters, e);
        }
        finally
        { // 关闭服务输入流和输出流
            FileUtilbc.close(is, dos);
        }
        return token;
    }
    
    /**
     * *********************************************************** <br>
     * *说明：需要插入數據 select * from sm_oauth_security<br>
     * @see ThirdPartyLoginVerfiyAction 校驗token<br>
     * @param ncchttp
     * @param datasource 数据源
     * @param usercode 用户编码
     * @param busicentercode 账套编码
     * @param client_id 第三方系统id
     * @param client_security 第三方密钥
     * @return
     * @throws Exception <br>
     * @String <br>
     * @methods pers.bc.utils.yonyou.NCSSOUtil#genThirdPartyAccessToken <br>
     * @author LiBencheng <br>
     * @date Created on 2025年6月5日 <br>
     * @time 下午8:15:14 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static String genThirdPartyAccessToken(String baseurl, String datasource, String usercode, String busicentercode,
            String client_id, String client_security) throws Exception
    {
        String ts = (System.currentTimeMillis() + "").substring(0, 6);
        String key = usercode + client_security + ts;
        StringBuffer sb = new StringBuffer();
        String security = new Base64().encodeToString(SignatureTookKit.digestSign(usercode.getBytes("UTF-8"), key.getBytes("UTF-8")));
        sb.append("type=type_security");
        sb.append("&dsname=").append(datasource);// 数据源的编码，本地开发为design
        sb.append("&usercode=").append(usercode);// 用户的编码
        sb.append("&busicentercode=").append(busicentercode);// 账套编码，本地开发时为develop
        sb.append("&client_id=").append(client_id);// 第三方系统id
        sb.append("&security=").append(URLEncoder.encode(security, "UTF-8"));// 第三方秘钥
        sb.append("&ts=").append(ts);
        String token = "";
        String str = sb.toString().replaceAll("\\+", "%2B");// 避免出现特殊符号问题。
        OutputStream os = null;
        DataOutputStream dos = null;
        InputStream is = null;
        try
        {
            String url = baseurl + "/service/genThirdPartyAccessToken";
            URL preUrl = new URL(url);
            URLConnection uc = preUrl.openConnection();
            uc.setDoOutput(true);
            uc.setUseCaches(false);
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            uc.setRequestProperty("Content-Length", "10000");
            uc.setRequestProperty("Accept-Charset", "UTF-8");
            HttpURLConnection hc = (HttpURLConnection) uc;
            hc.setRequestMethod("POST");
            
            // sb.append("type=type_security&dsname=" + datasource + "&usercode=" + usercode +
            // "&busicentercode=" + busicentercode
            // + "&client_id=" + client_id + "&security=" + URLEncoder.encode(security, "UTF-8") + "&ts=" +
            // ts);
            os = hc.getOutputStream();
            dos = new DataOutputStream(os);
            dos.writeBytes(str);
            dos.flush();
            is = hc.getInputStream();
            int ch;
            while ((ch = is.read()) != -1)
            {
                token += String.valueOf((char) ch);
            }
            return token;
        }
        catch (Exception e)
        {
            throw new BusinessException("获取NCC验证token结果异常，參數：" + sb, e);
        }
        finally
        {
            FileUtilbc.close(dos, os, is);
        }
    }
    
    private String cfgFilePath = RuntimeEnv.getInstance().getNCHome() + File.separator + "modules" + File.separator + "ncsso"
        + File.separator + "META-INF" + File.separator + "ncssocfg.properties";
    
    public static NCSSOUtil getInstance()
    {
        if (null == SSOKeyUtil) SSOKeyUtil = new NCSSOUtil();
        return SSOKeyUtil;
    }
    
    public NCSSOUtil()
    {
        try
        {
            configMap = PropertiesUtil.getAllProperties(cfgFilePath);
        }
        catch (IOException e)
        {
        }
    }
    
    public String getBaseAddr(HttpServletRequest request)
    {
        String scheme = request.getScheme();
        String servername = request.getServerName();
        int serverport = request.getLocalPort();
        if (serverport == 80)
        {
            return scheme + "://" + servername;
        }
        else
        {
            return scheme + "://" + servername + ":" + serverport;
        }
    }
    
    public boolean ssoRegisterNC(String user_code, String key, String registerUrl)
    {
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        try
        {
            if (user_code != null && user_code.trim().length() > 0)
            {
                URL httpurl = new URL(registerUrl);
                HttpURLConnection con = (HttpURLConnection) httpurl.openConnection();
                
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                con.setUseCaches(false);
                
                osw = new OutputStreamWriter(con.getOutputStream(), "GBK");
                
                StringBuffer requestParam = new StringBuffer();
                requestParam.append("ssoKey=").append(key);
                requestParam.append("&userCode=").append(user_code);
                if (configMap.get("groupcode") != null)
                {
                    requestParam.append("&groupCode=").append(configMap.get("groupcode"));
                }
                if (configMap.get("busicenter") != null)
                {
                    requestParam.append("&busiCenter=").append(configMap.get("busicenter"));
                }
                
                osw.write(requestParam.toString());
                osw.flush();
                
                StringBuffer sb = new StringBuffer();
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String text = "";
                while ((text = br.readLine()) != null)
                {
                    sb.append(text);
                }
                
                return sb.toString().indexOf(key) != -1;
            }
        }
        catch (Exception e)
        {
            LoggerUtil.getInstance("ncssologs", "ncssoutil").exception(e);
        }
        finally
        {
            FileUtilbc.close(br, osw);
        }
        
        return false;
    }
    
    /**
     * 单点自助
     */
    public String ssoRegisterHRSS(String user_code, String key, String registerUrl)
    {
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        String ssokey = null;
        try
        {
            if (user_code != null && user_code.trim().length() > 0)
            {
                URL httpurl = new URL(registerUrl);
                HttpURLConnection con = (HttpURLConnection) httpurl.openConnection();
                
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                con.setUseCaches(false);
                
                osw = new OutputStreamWriter(con.getOutputStream(), "GBK");
                StringBuffer requestParam = new StringBuffer();
                requestParam.append("&userid=").append(user_code);
                // requestParam.append("&password=").append(userPasswd);
                // if (getDataSource() != null) {
                // requestParam.append("&dsname=").append(getDataSource());
                // }
                requestParam.append("&needverifypasswd=").append("N");
                requestParam.append("&type=").append("2");
                osw.write(requestParam.toString());
                osw.flush();
                
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String str = br.readLine();
                
                String[] strs = str.split(":");
                ssokey = strs[1];
                
            }
        }
        catch (Exception e)
        {
            LoggerUtil.getInstance("ncssologs", "ncssoutil").exception(e);
        }
        finally
        {
            FileUtilbc.close(br, osw);
        }
        
        return ssokey;
    }
    
    /**
     * 单点NC获取ssoKey
     */
    public String ssoRegister4NC(String user_code, String key, String registerUrl)
    {
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        String ssokey = null;
        try
        {
            if (user_code != null && user_code.trim().length() > 0)
            {
                URL httpurl = new URL(registerUrl);
                HttpURLConnection con = (HttpURLConnection) httpurl.openConnection();
                
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                con.setUseCaches(false);
                
                osw = new OutputStreamWriter(con.getOutputStream(), "GBK");
                StringBuffer requestParam = new StringBuffer();
                // 获取NC注册登陆的ssoKey,注册时不需要添加ssoKey
                // requestParam.append("ssoKey=").append(key);
                requestParam.append("&userCode=").append(user_code);
                if (configMap.get("groupcode") != null && !configMap.get("groupcode").isEmpty())
                {
                    requestParam.append("&groupCode=").append(configMap.get("groupcode"));
                }
                if (configMap.get("busicenter") != null && !configMap.get("busicenter").isEmpty())
                {
                    requestParam.append("&busiCenter=").append(configMap.get("busicenter"));
                }
                osw.write(requestParam.toString());
                osw.flush();
                
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String str = br.readLine();
                
                // String[] strs = str.split(":");
                ssokey = str;
            }
        }
        catch (Exception e)
        {
            LoggerUtil.getInstance("ncssologs", "ncssoutil").exception(e);
        }
        finally
        {
            FileUtilbc.close(br, osw);
        }
        
        return ssokey;
    }
    
    /**
     * 单点自助(员工刷卡单点)
     */
    public String ssoRegister4CSSC(String user_code, String key, String registerUrl)
    {
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        String ssokey = null;
        
        try
        {
            if (user_code != null && user_code.trim().length() > 0)
            {
                
                URL httpurl = new URL(registerUrl);
                HttpURLConnection con = (HttpURLConnection) httpurl.openConnection();
                
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                con.setUseCaches(false);
                
                osw = new OutputStreamWriter(con.getOutputStream(), "GBK");
                StringBuffer requestParam = new StringBuffer();
                // String ncLoginApproveUrl = baseAddr +
                // "/portal/pt/home/view?pageModule=weberm&pageName=MYEXPPORTAL";
                requestParam.append("&pageModule=").append("weberm");
                requestParam.append("&pageName=").append("MYEXPPORTAL");
                requestParam.append("&userid=").append(user_code);
                // requestParam.append("&password=").append(userPasswd);
                if (configMap.get("datasource") != null)
                {
                    requestParam.append("&dsname=").append(configMap.get("datasource"));
                }
                requestParam.append("&needverifypasswd=").append("N");
                requestParam.append("&type=").append("2");
                osw.write(requestParam.toString());
                osw.flush();
                
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String str = br.readLine();
                
                String[] strs = str.split(":");
                ssokey = strs[1];
            }
        }
        catch (Exception e)
        {
            LoggerUtil.getInstance("ncssologs", "ncssoutil").exception(e);
        }
        finally
        {
            FileUtilbc.close(br, osw);
        }
        return ssokey;
    }
    
    /**
     * 单点自助 并且打开对应待办
     */
    public String ssoWorkHRSS(String user_code, String key, String registerUrl)
    {
        // byte[] token = NCLocator.getInstance().lookup(IFwLogin.class).login("wangr", "qqq111", null);
        String ssokey = ssoRegisterHRSS(user_code, key, registerUrl);
        // String ncLoginUrl = "http://127.0.0.1:7777/portal/pt/home/index?ssoKey=" + ssokey;
        // try
        // {
        // URL url = new URL(ncLoginUrl);
        // URLConnection con = url.openConnection();
        // BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
        //
        // }
        // catch (Exception e)
        // {
        // return "";
        // }finally {
        //
        // }
        return ssokey;
        
    }
    
    public String getPortalTaskUrlByTaskID(String taskid)
    
    {
        
        ITaskQryTmp taskQry = TaskHelper.getTaskQry("wfmtaskqry");
        
        // ITaskQryTmp taskQry = new HrssWfmTaskQryTmpImpl();
        
        TaskProcessUI tpi = taskQry.getTaskProcessUrl(taskid);
        
        String url = "";
        
        if (tpi != null)
        
        {
            String portal = LfwRuntimeEnvironment.getWebContext().getRequest().getRequestURL().toString();
            
            portal = portal.substring(0, portal.indexOf("/portal"));
            
            url = portal + tpi.getUrl();
            
        }
        
        return url;
        
    }
    
}
